import { defineStore } from 'pinia'
import LZString from 'lz-string'

interface GameState {
  isGameOver: boolean
  score: number
  highScore: number
}

const useGameStore = defineStore('game', {
  state: (): GameState => ({
    isGameOver: false,
    score: 0,
    highScore: loadHighScore(),
  }),
  
  actions: {
    setGameState(newState: Partial<GameState>) {
      this.$patch(state => {
        Object.assign(state, newState)
        
        // 自动持久化最高分
        if (newState.highScore !== undefined && newState.highScore !== state.highScore) {
          saveHighScore(newState.highScore)
        }
      })
    },
    
    reset() {
      this.$patch({
        isGameOver: false,
        score: 0,
        highScore: loadHighScore()
      })
    }
  }
})

// 工具函数
function loadHighScore(): number {
  const saved = localStorage.getItem('highScore')
  return saved ? parseInt(LZString.decompress(saved)) : 0
}

function saveHighScore(score: number): void {
  localStorage.setItem(
    'highScore', 
    LZString.compress(score.toString())
  )
}

export default useGameStore